package cn.com.chengmandian.company.utils;

import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.common.enums.ClientsEnum;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.CompanyInfo;
import cn.com.chengmandian.core.web.pojo.CompanyUser;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.core.web.utils.SpringContextUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class AuthUtil {

    /**
     * 获取用户信息
     */
    public static CompanyUser getCompanyUser(String token, CompanyInfo companyInfo) {
        if (!JWTUtil.verify(token, companyInfo.getTokenSecret().getBytes())) {
            if (SpringContextUtil.isDev()) {
                log.error("Token验证未通过：{}", token);
            }
            return null;
        }
        JWT jwt = JWTUtil.parseToken(token);
        CompanyUser companyUser = jwt.getPayloads().toBean(CompanyUser.class);
        if (companyUser == null) return null;
        if (SpringContextUtil.isDev()) {
            log.info("Token：{}", JSONUtil.toJsonStr(companyUser));
        }

        if (companyUser.getExpireDate() < DateUtil.date().getTime()) {
            log.info("Token已过期：{}", token);
            return null;
        }
        return companyUser;
    }

    public static CompanyUser getCompanyUser(HttpServletRequest request, ClientsEnum client, CompanyInfo companyInfo) {
        String token = request.getHeader(client.getHeaderName());
        if (StrUtil.isBlank(token)) return null;
        return getCompanyUser(request.getHeader(client.getHeaderName()), companyInfo);
    }

    /**
     * 获取当前登陆用户
     * @return
     */
    public static CompanyUser getCompanyUser() {
        HttpServletRequest request = ServletUtil.getRequest();
        CompanyInfo companyInfo = LocalMapUtil.getCompanyInfo();
        if (companyInfo == null) return null;
        String clientId = request.getHeader(CommonConstant.HEADER_CLIENT_ID);
        if (StrUtil.isBlank(clientId)) return null;
        ClientsEnum client = ClientsEnum.codeOf(clientId);
        if (client == null) return null;
        return getCompanyUser(request, client, companyInfo);
    }

    public static <T> T get(String key) {
        CompanyUser user = getCompanyUser();
        if (user.getAttrs() == null || !user.getAttrs().containsKey(key)) return null;
        return (T)user.getAttrs().get(key);
    }
}
